package com.yunze.system.cwgl;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import com.yunze.common.mapper.mysql.YzCardFlowMapper;
import com.yunze.common.mapper.mysql.YzExecutionTaskMapper;
import com.yunze.common.utils.yunze.WriteCSV;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 入款详情导出
 */

@Slf4j
@Component
public class ExportIncomeArr {

    @Resource
    private YzExecutionTaskMapper yzExecutionTaskMapper;
    @Resource
    private WriteCSV writeCSV;
    @Resource
    private YzCardFlowMapper yzCardFlowMapper;


    @RabbitHandler
    @RabbitListener(queues = "admin_ExportIncome_queue")
    public void DbCard(String msg, Channel channel) throws IOException {
        try {
            if (StringUtils.isEmpty(msg)) {
                return;
            }
            Map<String, Object> Pmap = JSON.parseObject(msg);
            //System.out.println(Pmap);
            Map<String, Object> map = (Map<String, Object>) Pmap.get("map");
            Map<String, Object> User = (Map<String, Object>) Pmap.get("User");
            List<Map<String, Object>> outCardIccidArr = (List<Map<String, Object>>) Pmap.get("outCardIccidArr");
            List<Map<String, Object>> userArr = (List<Map<String, Object>>) Pmap.get("userArr");
            List<Map<String, Object>> stateArr = (List<Map<String, Object>>) Pmap.get("stateArr");

            List<Map<String, Object>> zhangHuArr = new ArrayList<>();
            List<Map<String, Object>> FatNameArr = (List<Map<String, Object>>) Pmap.get("FatNameArr");
            List<Map<String, Object>> sleName = (List<Map<String, Object>>) Pmap.get("sleName");

            // 前端是把两个数组合并 后端处理 FatNameArr 和 sleName 放到 zhangHuArr 数组
            zhangHuArr.addAll(FatNameArr);
            if(sleName!=null && sleName.size()>0){
                zhangHuArr.addAll(sleName);
            }


            String newName = (String) Pmap.get("newName");
            Map<String, Object> task_map = (Map<String, Object>) Pmap.get("task_map");

            //执行前判断 redis 是否存在 执行数据 存在时 不执行
            OutDataCard(map, User, outCardIccidArr, userArr, newName, task_map, stateArr, zhangHuArr);

        } catch (Exception e) {
            log.error(">>错误 - 入款信息导出 消费者:{}<<", e.getMessage().toString());
        }
    }

    private void OutDataCard(Map<String, Object> map, Map<String, Object> user, List<Map<String, Object>> outCardIccidArr,
                             List<Map<String, Object>> userArr, String newName, Map<String, Object> task_map, List<Map<String, Object>> stateArr,
                             List<Map<String, Object>> zhangHuArr) {

        yzExecutionTaskMapper.add(task_map);//添加执行 任务表
        Map<String, Object> Dept = (Map<String, Object>) user.get("dept");
        String agent_id = Dept.get("deptId").toString();
        if (agent_id.equals("100")) {
            yzCardFlowMapper.queryPackage_simple(map);
        } else {
            Map<String, Object> PackageMap = new HashMap<String, Object>();
            PackageMap.put("agent_id", agent_id);
            yzCardFlowMapper.queryAgentPackage_simple(PackageMap);
        }
        map.put("iccid_arrs", outCardIccidArr);

        try {
            WriteOutCard(outCardIccidArr, userArr, newName, task_map, stateArr, map, user,zhangHuArr);
        } catch (Exception e) {
            log.error("导出卡信息异常 [导出数据 Exception] " + e.getCause().toString());
        }
    }


    /**
     * 字典获取
     *
     * @param CarMap      写入Map
     * @param DictDataArr 字典 list
     * @param basis       获取依据 字段 与 dictValue 判断
     * @param fieldName   返回字段名称
     * @return
     */
    public Map<String, Object> WriteDic(Map<String, Object> CarMap, List<Map<String, Object>> DictDataArr, String basis, String fieldName) {

        Map<String, Object> Rmap = new HashMap<String, Object>();
        String status_id = CarMap.get(basis) != null ? CarMap.get(basis).toString() : null;
        boolean bool = false;
        if (status_id != null) {
            for (int i = 0; i < DictDataArr.size(); i++) {
                Map<String, Object> dictData = DictDataArr.get(i);
                String dictValue = dictData.get("dictValue").toString();
                if (dictValue.equals(status_id)) {
                    CarMap.put(fieldName, dictData.get("dictLabel"));
                    bool = true;
                    break;
                }
            }
        }
        //字段 默认值
        if (!bool) {
            CarMap.put(fieldName, "");
        }
        return CarMap;
    }

    /**
     * 写入 查询 公司账户信息
     */
    protected Map<String, Object> WriteFatName(Map<String, Object> CarMap, List<Map<String, Object>> sleName) {

        String Fat_ID = CarMap.get("dictValue") != null ? CarMap.get("dictValue").toString() : null;
        boolean bool = false;
        if (sleName != null && Fat_ID != null) {
            for (int i = 0; i < sleName.size(); i++) {
                Map<String, Object> UserMap = sleName.get(i);
                String Fuser_id = UserMap.get("dictValue").toString();
                if (Fuser_id.equals(Fat_ID)) {
                    CarMap.put("dictLabel", UserMap.get("dictLabel"));
                    bool = true;
                    break;
                }
            }
        }
        if (!bool) {
            CarMap.put("dictLabel", "");
        }
        return CarMap;
    }


    private String WriteOutCard(List<Map<String, Object>> outCardArr, List<Map<String, Object>> userArr,
                                String newName, Map<String, Object> task_map, List<Map<String, Object>> stateArr, Map<String, Object> map,
                                Map<String, Object> user, List<Map<String, Object>> zhangHuArr) {

        List<Map<String, Object>> out_list = new ArrayList<Map<String, Object>>();
        //循环添加单卡数据信息
        for (int i = 0; i < outCardArr.size(); i++) {
            Map<String, Object> CarMap = outCardArr.get(i);

            //写入 支付方式 pay_type_value
            CarMap = WriteDic(CarMap, stateArr, "Dio_DsID", "Dio_DsID_value");
            CarMap = WriteDic(CarMap, zhangHuArr, "Dids_FatName", "Dids_FatName_value");
            out_list.add(CarMap);
        }


        String Outcolumns[] = {"公司账户", "入款日期", "合同日期", "单位", "销售单位", "工程师", "合同金额", "入款金额", "实际金额", "未到金额", "入款状态", "入款合计", "备注"};
        String keys[] = {"Dids_FatName_value", "Dids_Time", "c_time", "c_name", "c_fatName", "c_userName", "c_contract_amount", "Dids_Amount", "c_the_actual_amount",
                "Dio_Unpaid", "Dio_DsID_value", "Dio_Deposit_Total", "Dids_Remarks"};
        writeCSV.Write(newName, out_list, Outcolumns, null, keys);
        yzExecutionTaskMapper.set_end_time(task_map);//任务结束
        return "已下发执行日志可在【系统管理】》【日志管理】》【执行日志】查看";

    }


}





